package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/18 13:26
 */

//基于UDP通信的接收端 A
public class UDPReceiveA {

    public static void main(String[] args) throws IOException {

        //1.创建一个DatagramSocket对象，准备在9999端口接收数据
        DatagramSocket socket = new DatagramSocket(9999);

        //2.创建一个DatagramPacket对象，使用DatagramSocket接收数据
        //udp通信中，一个数据包最大为64k
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        //3.调用receive方法，接收网络传输的datagramSocket对象。
        //如果接收到了网络中的datagramSocket对象，就继续向下执行，否则阻塞在receive方法中
        System.out.println("接收端A等待网络中的DatagramPacket");
        socket.receive(packet);

        //4.将接收到的DatagramSocket对象进行拆包
        int length = packet.getLength();
        byte[] data = packet.getData();
        System.out.println(new String(data,0,length));

        //5.接收到数据后，回复"收到、明天见"
        byte[] bytes = "收到，明天见".getBytes();
        packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("192.168.171.1"),9998);
        socket.send(packet);

        //关闭资源
        socket.close();
    }
}
